package com.chookss.home.audit.service;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.InspectionEntity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UploadInspectionService extends Service {

    public static int NotificationId = 5;
    private ArrayList<InspectionEntity> allList = new ArrayList<>();
    private boolean beginUpload=false;//上传中不得重新开始
    private boolean stopUpload=false;//默认正常上传  当true时切换账号中止上传
    private int numAll = 0;
    private ArrayList<Map<String, String>> urlListMaps = new ArrayList<>();
    private int picUploadStatus=0;//图片上传状态,默认为0，当失败的时候递增，失败最多重试3次

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initNotification();
        EventBus.getDefault().register(this);
        registerBoradcastReceiver();
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        InspectionEntity inspectionEntity = (InspectionEntity) intent.getSerializableExtra("inspectionEntity");
        if (inspectionEntity != null) {
            allList.add(inspectionEntity);
            setNewData();
        }
        return super.onStartCommand(intent, flags, startId);
    }
    private void setNewData() {
        if(!beginUpload){
            beginUpload=true;
            urlListMaps.clear();
            numAll=0;
            for (int i = 0; i < allList.get(0).getPicList().size(); i++) {
                Map<String, String> map = new HashMap<>();
                map.put("picturePath", "");
                map.put("thumbnailPath", "");
                urlListMaps.add(map);
            }
            uploadPicData();
        }
    }
    private void uploadPicData() {
        if(stopUpload){
            Message msg = handler.obtainMessage();
            msg.arg1 = 100;
            handler.sendMessage(msg);
            stopSelf();
            return;
        }
        String picUrl = allList.get(0).getPicList().get(numAll);
        if (Utils.isNull(picUrl)) {
            numAll++;
            if (numAll == allList.get(0).getPicList().size()) {
                //图片上传完毕
                uploadData();
            }
        } else {
            int y = numAll;
            File file = new File(picUrl);
            MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "2", file, new JsonCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    JSONObject result = null;
                    JSONObject data = null;
                    picUploadStatus=0;
                    try {
                        result = new JSONObject(response.body().toString());
                        if (result.getString("code").equals("200")) {
                            data = result.getJSONObject("data");
                            numAll++;
                            Message msg = handler.obtainMessage();
                            int size=allList.get(0).getPicList().size();
                            if(Utils.isNull( allList.get(0).getPicList().get(size-1))){
                                msg.arg1 = (numAll * 100) / (allList.get(0).getPicList().size()-1);
                            }else{
                                msg.arg1 = (numAll * 100) / allList.get(0).getPicList().size();
                            }
                            handler.sendMessage(msg);
                            FileUtilss.delFile(picUrl);
                            urlListMaps.get(y).put("picturePath", data.getString("originalUrl"));
                            if (numAll == allList.get(0).getPicList().size()) {
                                //图片上传完毕
                                uploadData();
                            } else {
                                uploadPicData();
                            }
                        } else if (result.getString("code").startsWith("400")) {
                            Message msg = handler.obtainMessage();
                            msg.arg1 = 100;
                            handler.sendMessage(msg);
                            MyToast.show("巡检图片上传异常，请稍后重试");
                            OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                            stopSelf();
                        } else {
                            Message msg = handler.obtainMessage();
                            msg.arg1 = 100;
                            handler.sendMessage(msg);
                            MyToast.show(result.getString("msg"));
                            stopSelf();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Message msg = handler.obtainMessage();
                        msg.arg1 = 100;
                        handler.sendMessage(msg);
                        MyToast.show("巡检图片服务异常，请稍后重试");
                        stopSelf();
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    MyToast.show("巡检图片上传重试中");
                    if(picUploadStatus<3){
                        picUploadStatus++;
                        //重试3次
                        uploadPicData();
                    }else{
                        //第二次上传图片还是失败就放弃，直接下一张
                        picUploadStatus=0;
                        numAll++;
                        Message msg = handler.obtainMessage();
                        int size=allList.get(0).getPicList().size();
                        if(Utils.isNull( allList.get(0).getPicList().get(size-1))){
                            msg.arg1 = (numAll * 100) / (allList.get(0).getPicList().size()-1);
                        }else{
                            msg.arg1 = (numAll * 100) / allList.get(0).getPicList().size();
                        }
                        handler.sendMessage(msg);
                        FileUtilss.delFile(picUrl);
                        urlListMaps.get(y).put("picturePath","");
                        if (numAll == allList.get(0).getPicList().size()) {
                            //图片上传完毕
                            uploadData();
                        } else {
                            uploadPicData();
                        }
                    }

                }
            });
        }
    }

    private void uploadData() {
        if(stopUpload){
            Message msg = handler.obtainMessage();
            msg.arg1 = 100;
            handler.sendMessage(msg);
            stopSelf();
            return;
        }
        List<String> pics = new ArrayList<>();
        for (int i = 0; i < urlListMaps.size(); i++) {
            if (!Utils.isNull(urlListMaps.get(i).get("picturePath"))) {
                pics.add(urlListMaps.get(i).get("picturePath"));
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("employeeName", new ShareUtils().getString(this, StaticClass.USER_NICKNAME, ""));
        map.put("employeeCode", new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
        map.put("groupCode", allList.get(0).getGroupCode());
        map.put("groupName", allList.get(0).getGroupName());
        map.put("companyCode", new ShareUtils().getString(this, StaticClass.COMPANYCODE, ""));
        map.put("companyName", new ShareUtils().getString(this, StaticClass.COMPANYNAME, ""));
        map.put("xunjianTime", Utils.getCurrentTime2());
        map.put("xunjianJd",  allList.get(0).getAddressAccuracyX());
        map.put("xunjianWd",  allList.get(0).getAddressAccuracyY());
        map.put("xunjianAddress",  allList.get(0).getAddressName());
        map.put("addressCode",  allList.get(0).getAddressCode());
        map.put("xunjianRemarks", allList.get(0).getXunjianRemarks());
        map.put("imglist", XJson.listStringToJsArray(pics));
        KLog.i(allList.get(0).getAddressAccuracyX());
        KLog.i(allList.get(0).getAddressAccuracyY());
        KLog.i(allList.get(0).getAddressName());
        MyHttpRequest.postRequestJson(Urls.insertXunjianInfo, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        if(allList.size()>1){
                            allList.remove(0);
                            beginUpload=false;
                            setNewData();
                        }else{
                            MyToast.show("上传成功");
                            EventBus.getDefault().post(new MyEvent("RefreshInspectionList"));
                            stopSelf();
                        }
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                        stopSelf();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("巡检服务接口失败，请稍后重试");
                    stopSelf();
                }
            }
        });
    }

    private NotificationManager mNManager;
    private Notification notification;

    private void initNotification() {
        //获得通知消息管理类对象
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Bitmap largeBitmap = GlideUtils.loadLogo(this);
        notification = new Notification(GlideUtils.loadLogoId(this), "带进条的提醒", System.currentTimeMillis());
//Android8.0以上必须添加 渠道 才能显示通知栏
        RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.vedio_upload);
        contentView.setProgressBar(R.id.progressbarUpload, 100, 0, false);
        contentView.setTextViewText(R.id.tvProcess, "已上传" + "0%");
        contentView.setImageViewResource(R.id.appdown_ivLogo, GlideUtils.loadLogoId(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道
            String id = "news_upload_channel";
            String name = getResources().getString(R.string.app_name);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mNManager.createNotificationChannel(mChannel);
            //设置图片,通知标题,发送时间,提示方式等属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
            int PROGRESS_MAX = 100;
            int PROGRESS_CURRENT = 0;
            builder.setCustomContentView(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        } else {
            //设置图片,通知标题,发送时间,提示方式等属性
            Notification.Builder builder = new Notification.Builder(this);
            builder.setContent(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        }
        mNManager.notify(NotificationId, notification);

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            notification.contentView.setProgressBar(R.id.progressbarUpload, 100, msg.arg1,
                    false);
            notification.contentView.setTextViewText(R.id.tvProcess, "已上传"
                    + msg.arg1 + "%");
            mNManager.notify(NotificationId, notification);
            if (msg.arg1 == 100) {
                mNManager.cancel(NotificationId);
            }
            super.handleMessage(msg);
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("Stop_File_Upload")) {
                //中止上传任务
                stopUpload = true;
            }
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (context != null && intent != null && intent.getAction() != null) {

                if (action.equals(StaticClass.ACCOUNT_OUT)) {
                    //账号退出所有 上传数据全部当做失败处理
                    stopSelf();
                }
            }
        }

    };

    private void registerBoradcastReceiver() {
        if (mBroadcastReceiver != null) {
            IntentFilter myIntentFilter = new IntentFilter();
            myIntentFilter.addAction(StaticClass.ACCOUNT_OUT);// 关闭
            //注册广播
            LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mNManager != null) {
            mNManager.cancel(NotificationId);
        }
        if (mBroadcastReceiver != null && this != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
        }
    }
}